import os
import subprocess
import logging as log
import re

basedir = os.path.dirname(os.path.abspath(__file__))


def run_cmd(cmd, information=None, file_output=None):
    """
    执行命令并发送初始信息给mq
    :param cmd: 执行的备份命令
    :param information: 备份信息实例
    :param file_output: 输出文件流
    :return:
    """
    log.debug(cmd)
    if file_output is None:
        stdout = subprocess.PIPE
        stderr = subprocess.STDOUT
    else:
        stdout = file_output
        stderr = file_output
    p = subprocess.Popen(cmd,
                         shell=True,
                         stdout=stdout,
                         stderr=stderr)
    pid = p.pid
    try:
        information.set_pid_info(pid=pid)
        information.backup_startup_publish()
    except AttributeError as e:
        pass
    # result = p.stdout.read()
    return_code = p.wait()
    return return_code


def get_ip_port(backup_file_path):
    backup_file_path1 = backup_file_path.replace('//', '/')
    path_list = backup_file_path1.split('/')
    for i in path_list:
        try:
            ip_port_list = i.split('_')
            host = ip_port_list[0]
            port = ip_port_list[1]
            if check_ip(host) and port.isdigit():
                return i
        except IndexError:
            pass


def get_trans_command(backup_file_path, **kwargs):
    default_bwlimit = 2000
    remote_host = kwargs.get('remote_host')
    remote_rsync_module = kwargs.get('remote_rsync_module')
    remote_rsync_port = kwargs.get('remote_rsync_port', 22003)
    rsync_user = kwargs.get('rsync_user', 'dba_rsync')
    rsync_secret = kwargs.get('rsync_secret', 'rsync.secret')
    bwlimit = kwargs.get('bwlimit', default_bwlimit)
    ip_port = get_ip_port(backup_file_path)
    rsync_command = "rsync -avz --password-file={basedir}/{rsync_secret} --bwlimit={bwlimit} --port={remote_rsync_port} {backup_file_path} " \
                    "{rsync_user}@{remote_host}::{remote_rsync_module}/{ip_port}" \
        .format(basedir=basedir,
                backup_file_path=backup_file_path,
                rsync_user=rsync_user,
                remote_host=remote_host,
                remote_rsync_module=remote_rsync_module,
                rsync_secret=rsync_secret,
                remote_rsync_port=remote_rsync_port,
                ip_port=ip_port,
                bwlimit=bwlimit)
    return rsync_command


def check_ip(ip):
    p = re.compile('^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$')
    if p.match(ip):
        return True
    else:
        return False


def file_file_transfer(backup_file_path_list, **kwargs):
    for backup_file_path in backup_file_path_list:
        file_transfer_command = get_trans_command(backup_file_path, **kwargs)
        run_cmd(file_transfer_command)


if __name__ == "__main__":
    backuppath = "/data/mongodb_backup//10.1.1.232_40002/2020_06161643"
    print(get_ip_port(backuppath))
